import express from "express";
import http from "http";
const socketIo = require("socket.io");

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*", // 允许跨域的前端域名
    methods: ["GET", "POST"], // 允许的跨域请求方法
    transports: ["websocket", "polling"], // 允许的跨域通信传输方式
    credentials: true, // 允许cookies等认证信息一起跨域传递
  },
});

let onlineCounts: any = {};

io.on("connection", (socket: any) => {
  const site = socket.handshake.query.site;
  if (!onlineCounts[site]) {
    onlineCounts[site] = 0;
  }
  onlineCounts[site]++;
  console.log(`${site}----${onlineCounts[site]} 用户现在已连接`);
  socket.emit("update online", onlineCounts[site]);
  socket.broadcast.emit("update online", onlineCounts[site]);
  
  socket.on("disconnect", () => {
    onlineCounts[site]--;
    console.log(`${site}----${onlineCounts[site]} 用户现在已断开连接`);
    socket.broadcast.emit("update online", onlineCounts[site]);
  });
});

server.listen(9999, () => {
  console.log("服务器运行在 http://localhost:9999/");
});
